﻿using System;
using System.Collections.Generic;
using System.Net;
using Microsoft.TeamFoundation.Client;
using TfsUtils.Utils;
using TfsUtils.Utils.Concrete;

namespace TfsUtils.Commands
{
    public abstract class BaseCommand : ICommand
    {
        protected BaseCommand()
        {
            _parameterValues = new Dictionary<string, object>();
            Environment = NullEnvironment.Instance;
        }

        public String UserName { get; set; }

        public String Password { get; set; }

        public String CollectionUrl { get; set; }

        public IEnvironment Environment { get; set; }

        public int Execute()
        {

            return OnExecute();
        }

        internal abstract Int32 OnExecute();

        protected Dictionary<String, Object> _parameterValues;

        public void SetParameters(System.Collections.Generic.List<Parameter> commonParameters, string[] parameters)
        {
            foreach (Parameter commonParameter in commonParameters)
            {
                commonParameter.Fill(_parameterValues, parameters);
            }
        }

        protected T GetParameterValue<T>(String name)
        {
            return (T)_parameterValues[name];
        }

        protected TfsTeamProjectCollection CreateTfsTeamProjectCollection()
        {
            string userName = GetParameterValue<String>("user");
            string password = GetParameterValue<String>("pwd");
            Uri projectCollection = new Uri(GetParameterValue<String>("collection"));
            TfsTeamProjectCollection tfsTeamProjectCollection = 
                new TfsTeamProjectCollection(projectCollection,
                new NetworkCredential(userName, password));
            string message = "Created connection to " + projectCollection.AbsoluteUri;
            SendMessage(message); 
            return tfsTeamProjectCollection;
        }

        protected void SendMessage(string message)
        {
            Environment.SendMessage(message, MessageLevel.Message);
        }

        protected void SendInfo(string message)
        {
            Environment.SendMessage(message, MessageLevel.Info);
        }

        protected void SendDebug(string message)
        {
            Environment.SendMessage(message, MessageLevel.Debug);
        }

        protected void SendWarn(string message)
        {
            Environment.SendMessage(message, MessageLevel.Warn);
        }
    }
}
